VFS.Include("luarules/utils/table_utils.lua")

local max = math.max
local Shared = Shared

Shared.copyTable = copyTable

function Shared.CreateWeaponWithMoreBarrels (newWeapon, newName, newNumberOfBarrels, origWeapon, fireInBurstRate)
  local weaponDefs = Shared.weaponDefs
  if (type(weaponDefs) == "table" and weaponDefs[origWeapon]) then
    local newWeaponDef = copyTable(weaponDefs[origWeapon])
    newWeaponDef.customParams = newWeaponDef.customParams or {}
    local customParams = newWeaponDef.customParams
    
    if (fireInBurstRate) then
      local multiplier = 
        max(1, newNumberOfBarrels) /
        max(1, customParams.numberOfBarrels or 1)
      if (fireInBurstRate >= 0.001) then   --[[ and (burst <= 1 or burstRate <= fireInBurstRate)--]] 
        newWeaponDef.burst       = math.ceil((newWeaponDef.burst       or 1) * multiplier)
        newWeaponDef.burstRate   = fireInBurstRate
      else
        newWeaponDef.projectiles = math.ceil((newWeaponDef.projectiles or 1) * multiplier)  
      end
    else
      local barrelsPenalty = customParams.barrelsPenalty or 0.0   
      newWeaponDef.reloadTime = 
        (newWeaponDef.reloadTime or newWeaponDef.reloadtime or 1.0) * 
        max(1, (customParams.numberOfBarrels or 1) + barrelsPenalty) /
        max(1, newNumberOfBarrels + barrelsPenalty)
    end
    
    newWeaponDef.name = newName    
    customParams.numberOfBarrels = newNumberOfBarrels 
      
    weaponDefs[newWeapon] = newWeaponDef
  else
    Spring.Echo('[weapon_utils.lua] Error: No weapon of name "' .. origWeapon .. '"')
  end
end
